package com.wb.mas.ui.login;

import android.app.Application;
import android.text.TextUtils;

import com.appsflyer.AFInAppEventParameterName;
import com.appsflyer.AppsFlyerLib;
import com.blankj.utilcode.util.SPUtils;
import com.facebook.accountkit.AccessToken;
import com.facebook.accountkit.AccountKit;
import com.wb.mas.BuildConfig;
import com.wb.mas.app.SPKeys;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.LoginResponse;
import com.wb.mas.entity.LoginTypeResponse;
import com.wb.mas.ui.main.MainViewModel;
import com.wb.mas.utils.response.ResultException;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class LoginViewModel extends BaseViewModel<DemoRepository> {

    public UiChangeEvent uc = new UiChangeEvent();

    public LoginViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
    }


    public UiChangeEvent ui = new UiChangeEvent();

    public class UiChangeEvent {
        public SingleLiveEvent<String> showLoginUiEvent = new SingleLiveEvent();
        public SingleLiveEvent<String> loginSucEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<String> loginEvent = new SingleLiveEvent<>();


    }

    @Override
    public void onCreate() {
        super.onCreate();

//        showLoginUI();
        getLoginType();
    }

    private void getLoginType() {
        showDialog();
        model.getLoginType(new HashMap<String, Object>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LoginTypeResponse>() {
                    @Override
                    public void accept(LoginTypeResponse loginResponse) throws Exception {

                        dismissDialog();
                        KLog.i("request suc");
                        if (loginResponse != null && !StringUtils.isEmpty(loginResponse.getData())) {
                            if ("2".equalsIgnoreCase(loginResponse.getData())) {
                                jumpToPhoneLoginPage();
                            } else {
                                showLoginUI();
                            }
                        } else {

                            showLoginUI();
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        dismissDialog();
                        showLoginUI();
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                        KLog.e("request failed");
                    }
                });

    }

    private void jumpToPhoneLoginPage() {
        startActivity(LoginByPhoneAc.class);
        finish();
    }

    private void showLoginUI() {
        ui.showLoginUiEvent.setValue("");
    }

    public void login(Map<String, Object> param) {

        showDialog();
        model.login(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LoginResponse>() {
                    @Override
                    public void accept(LoginResponse loginResponse) throws Exception {

                        dismissDialog();
                        KLog.i("request suc");
                        if (loginResponse.getStatus() == 200) {

                            String token = loginResponse.getData().getToken();
                            SPUtils.getInstance().put(SPKeys.KEY_OF_TOKEN, token);
                            Messenger.getDefault().send("", MainViewModel.AUTH_SUC_EVENT);

                            uc.loginSucEvent.setValue("");
                            trackLoginEvent(loginResponse);
                        } else {

                            if (loginResponse != null && !TextUtils.isEmpty(loginResponse.getMessage())) {
                                ToastUtils.showShort(loginResponse.getMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        dismissDialog();
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                        KLog.e("request failed");
                    }
                });
    }


    private void trackLoginEvent(LoginResponse infoResponse) {
        if ("1".equalsIgnoreCase(infoResponse.getData().getUserType())) {
            //appflyers的埋点
            Map<String, Object> eventValue = new HashMap<>();
            eventValue.put(AFInAppEventParameterName.REGSITRATION_METHOD, "Facebook");
            eventValue.put("userId", infoResponse.getData().getId());
            AppsFlyerLib.getInstance().trackEvent(getApplication(),
                    "facebookLogin", eventValue);
        } else {
            //新用户注册
            Map<String, Object> eventValue = new HashMap<>();
            eventValue.put(AFInAppEventParameterName.REGSITRATION_METHOD, "Facebook");
            eventValue.put("userId", infoResponse.getData().getId());
            AppsFlyerLib.getInstance().trackEvent(getApplication(),
                    "facebookRegister", eventValue);
        }
    }

    public BindingCommand clickLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

//            String token = "AQBIA7-xQK1KJbliN-tB4fE_OIEcbJ8UaHbH_lF_RvhPVK5vLE8mG4gQMj_AZc9LV-T4Tbw-NOgC0E4zssUqjxckrP-4I8";
//            Map<String, Object> param = new HashMap<>();
//            param.put("channel", BuildConfig.channel);
//            param.put("authCode", token);
//            login(param);

            KLog.i("login clicked");
            AccessToken accessToken = AccountKit.getCurrentAccessToken();

            if (accessToken != null) {
                //Handle Returning User
                KLog.i("token not null,token is:" + accessToken.getToken());
                Map<String, Object> param = new HashMap<>();
                param.put("channel", BuildConfig.channel);
                param.put("authCode", accessToken.getToken());
                login(param);

            } else {
                KLog.i("token is null");
                uc.loginEvent.setValue("");

            }
        }
    });


    public BindingCommand replaceLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(LoginAccountActivity.class);
            finish();
        }
    });

}
